//
//  BDSettingTableViewController.m
//  BeidouMall
//
//  Created by qie on 16/3/31.
//  Copyright © 2016年 qie. All rights reserved.
//

#import "BDSettingTableViewController.h"
#import "UIScrollView+TwitterCover.h"
#import "BDOrderNavigationController.h"
#import "BDOrderHomeViewController.h"
#import "BDNavigationController.h"
#import "BDYouhuiHomeViewController.h"

@interface BDSettingTableViewController () <UITableViewDelegate>
{
    BOOL presentLoginView;
}
@property (weak, nonatomic) IBOutlet UIView *topView;
@property (weak, nonatomic) IBOutlet UILabel *userNameLabel;
@property (weak, nonatomic) IBOutlet UIButton *userImageButton;
@property (weak, nonatomic) IBOutlet UIButton *userSettingButton;
@property (weak, nonatomic) IBOutlet UIButton *userTitleButton;
@property (weak, nonatomic) IBOutlet UIImageView *userSettingImageView;

@property (weak, nonatomic) IBOutlet UITableViewCell *secondCell;

@property (weak, nonatomic) IBOutlet UILabel *firstNumLabel;
@property (weak, nonatomic) IBOutlet UILabel *secondNumLabel;
@property (weak, nonatomic) IBOutlet UILabel *thirdNumLabel;


@end

@implementation BDSettingTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.tableView addTwitterCoverWithImage:[UIImage imageNamed:@"setting_top_bg"] withFrame:CGRectMake(0, 0, kScreen_Width, CHTwitterCoverViewHeight)];
    //tableView上面多出来20个像素，是因为自动布局的缘故
    self.edgesForExtendedLayout = UIRectEdgeNone;
    CGFloat fontSize = kScreen_Width > 320 ? 12.0 : 11.0;
    if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"en"]) {
        for (UIView *view in _secondCell.contentView.subviews) {
            if ([view isKindOfClass:[UILabel class]]) {
                UILabel *label = (UILabel *)view;
                label.font = [UIFont systemFontOfSize:fontSize];
            }
        }
    }
    fontSize = kScreen_Width > 320 ? 8.0 : 7.0;
    if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"zang"]) {
        for (UIView *view in _secondCell.contentView.subviews) {
            if ([view isKindOfClass:[UILabel class]]) {
                UILabel *label = (UILabel *)view;
                label.font = [UIFont fontWithName:@"Bzdbt" size:fontSize];
            }
        }
    }
    
    _firstNumLabel.layer.cornerRadius = _firstNumLabel.width / 2;
    _firstNumLabel.layer.masksToBounds = YES;
    
    _secondNumLabel.layer.cornerRadius = _secondNumLabel.width / 2;
    _secondNumLabel.layer.masksToBounds = YES;
    
    _thirdNumLabel.layer.cornerRadius = _thirdNumLabel.width / 2;
    _thirdNumLabel.layer.masksToBounds = YES;
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // 设置状态栏样式 白色字
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];//UIStatusBarStyleDefault
    self.navigationController.navigationBarHidden = YES;
    
    if ([[BDAccountManagerModel shareInstance].payResult isEqualToString:@"selectTabBar"]) {
        [BDAccountManagerModel shareInstance].payResult = @"leisile";
        if ([BDAccountManagerModel shareInstance].login) {
            UIStoryboard *stroyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
            BDOrderNavigationController *nav_orderVc = [stroyboard instantiateViewControllerWithIdentifier:@"NavOrderStoryboardID"];
            nav_orderVc.mTabBarController = self.tabBarController;
            [self presentViewController:nav_orderVc animated:YES completion:nil];
        } else {
            [self performSegueWithIdentifier:@"loginSegue" sender:nil];
        }
    } else {
        if ([BDAccountManagerModel shareInstance].isLogin) {
            self.userNameLabel.hidden = NO;
            self.userTitleButton.hidden = YES;
            self.userNameLabel.text = [BDAccountManagerModel shareInstance].userName;
            [self.userImageButton setBackgroundImage:[UIImage imageNamed:@"userImg"] forState:UIControlStateNormal];
        } else {
            self.userNameLabel.hidden = YES;
            self.userTitleButton.hidden = NO;
            [self.userImageButton setBackgroundImage:[UIImage imageNamed:@"userImg_no"] forState:UIControlStateNormal];
        }
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if ([BDAccountManagerModel shareInstance].isLogin) {
        // 标记是否收货
        [self reloadData:nil andTag:102];
        [self reloadData:nil andTag:103];
        [self reloadData:nil andTag:104];
    } else {
        // 清除所有收货标记
        _firstNumLabel.hidden = YES;
        _secondNumLabel.hidden = YES;
        _thirdNumLabel.hidden = YES;
    }
    
}

- (void)dealloc {
    [self.tableView removeTwitterCoverView];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    // 设置状态栏样式 黑色字
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];//UIStatusBarStyleDefault
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    self.navigationController.navigationBarHidden = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.0;
}

#pragma mark - Private method

- (void)reloadData:(id) sender andTag:(NSUInteger) tag {
    NSString *url;
    // TO_PAY,PAYED,RECEIVING,SENDING,COMFIRM_RECEIVE,APPLY_REFUND,  ,REFUNDED,CANCEL,CLOSED
    switch (tag) {
        case 101:// 全部
            url = [NSString stringWithFormat:@"%@%@?userId=%@&currentPage=%ld&pageSize=%d",
                   [BDNetworking shareInstance].baseUrl,
                   Order_Query,
                   [BDAccountManagerModel shareInstance].userId,
                   (long)1,
                   300];
            break;
        case 102:// 待付款
            url = [NSString stringWithFormat:@"%@%@?status=%@&userId=%@&currentPage=%ld&pageSize=%d",
                   [BDNetworking shareInstance].baseUrl,
                   Order_Query,
                   @"TO_PAY",
                   [BDAccountManagerModel shareInstance].userId,
                   (long)1,
                   300];
            break;
        case 103:// 待发货
            url = [NSString stringWithFormat:@"%@%@?status=%@,%@&userId=%@&currentPage=%ld&pageSize=%d",
                   [BDNetworking shareInstance].baseUrl,
                   Order_Query,
                   @"PAYED",@"RECEIVING",
                   [BDAccountManagerModel shareInstance].userId,
                   (long)1,
                   300];
            break;
        case 104:// 待收货
            url = [NSString stringWithFormat:@"%@%@?status=%@&userId=%@&currentPage=%ld&pageSize=%d",
                   [BDNetworking shareInstance].baseUrl,
                   Order_Query,
                   @"SENDING",
                   [BDAccountManagerModel shareInstance].userId,
                   (long)1,
                   300];
            break;
        case 105:// 已收货
            url = [NSString stringWithFormat:@"%@%@?status=%@&userId=%@&currentPage=%ld&pageSize=%d",
                   [BDNetworking shareInstance].baseUrl,
                   Order_Query,
                   @"COMFIRM_RECEIVE",
                   [BDAccountManagerModel shareInstance].userId,
                   (long)1,
                   300];
            break;
        default:
            break;
    }
    [[BDNetworking shareInstance] postWithUrl:url sid:nil method:@"GET" parameters:nil completionHandler:^(NSObject *results, NSError *error) {
        if (error != nil) {
            NSLog(@"tag->订单查询失败:%lu%@",(unsigned long)tag,error);
            if ([[error localizedDescription] isEqualToString:@"登录超时"] && error.code == 401) {
                [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"Login timeout", nil)];
                if (!presentLoginView) {
                    presentLoginView = YES;
                    // 清除webViw cookie
                    NSHTTPCookie *cookie;
                    NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
                    for (cookie in [storage cookies])
                    {
                        [storage deleteCookie:cookie];
                    }
                    
                    [BDAccountManagerModel shareInstance].authorization = @"";
                    [BDAccountManagerModel shareInstance].login = NO;
                    UIStoryboard *stroyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
                    BDNavigationController *nav_addrVc = [stroyboard instantiateViewControllerWithIdentifier:@"navLoginStoryboardID"];
                    [self presentViewController:nav_addrVc animated:YES completion:nil];
                }
            }
        } else {
            if ([results isKindOfClass:[NSDictionary class]]) {
                NSLog(@"results = %@",results);
                NSDictionary *resultDic = (NSDictionary *)results;
                NSInteger number = [resultDic[@"number"] integerValue];
                _firstNumLabel.hidden = YES;
                _secondNumLabel.hidden = YES;
                _thirdNumLabel.hidden = YES;
                if (number > 0 && tag == 102) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        _firstNumLabel.hidden = NO;
                        _firstNumLabel.text = [NSString stringWithFormat:@"%ld",(long)number];
                        if (number > 19 && number < 100) {
                            _firstNumLabel.font = [UIFont systemFontOfSize:11.0];
                        } else if (number > 100) {
                            _firstNumLabel.font = [UIFont systemFontOfSize:9.0];
                            _firstNumLabel.text = [NSString stringWithFormat:@"99+"];
                        }
                    });
                }
                if (number > 0 && tag == 103) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        _secondNumLabel.hidden = NO;
                        _secondNumLabel.text = [NSString stringWithFormat:@"%ld",(long)number];
                        if (number > 19 && number < 100) {
                            _secondNumLabel.font = [UIFont systemFontOfSize:11.0];
                        } else if (number > 100) {
                            _secondNumLabel.font = [UIFont systemFontOfSize:9.0];
                            _secondNumLabel.text = [NSString stringWithFormat:@"99+"];
                        }
                    });
                }
                if (number > 0 && tag == 104) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        _thirdNumLabel.hidden = NO;
                        _thirdNumLabel.text = [NSString stringWithFormat:@"%ld",(long)number];
                        if (number > 19 && number < 100) {
                            _thirdNumLabel.font = [UIFont systemFontOfSize:11.0];
                        } else if (number > 100) {
                            _thirdNumLabel.font = [UIFont systemFontOfSize:9.0];
                            _thirdNumLabel.text = [NSString stringWithFormat:@"99+"];
                        }
                    });
                }
            }
        }
    }];
}

#pragma mark - IBActions

- (IBAction)userButtonPressed:(UIButton *)sender {
    if ([BDAccountManagerModel shareInstance].isLogin) {
        
    } else {
        [self performSegueWithIdentifier:@"loginSegue" sender:nil];
    }
}

- (IBAction)myAddrButtonPressed:(UIButton *)sender {
    if ([BDAccountManagerModel shareInstance].login) {
        [self performSegueWithIdentifier:@"myAddrSegue" sender:nil];
    } else {
        [self performSegueWithIdentifier:@"loginSegue" sender:nil];
    }
}

- (IBAction)userSettingButtonPressed:(UIButton *)sender {
    [self performSegueWithIdentifier:@"userSettingSegue" sender:nil];
}


- (IBAction)myOrderButtonPressed:(UIButton *)sender {
    if ([BDAccountManagerModel shareInstance].login) {
        UIStoryboard *stroyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
        BDOrderNavigationController *nav_orderVc = [stroyboard instantiateViewControllerWithIdentifier:@"NavOrderStoryboardID"];
        nav_orderVc.mTabBarController = self.tabBarController;
        BDOrderHomeViewController *orderVc = (BDOrderHomeViewController *)nav_orderVc.topViewController;
        orderVc.block = ^(NSString *str){// 用于从订单返回首页
            if ([str isEqualToString:@"success"]) {
                self.tabBarController.selectedIndex = 0;
            }
        };
        [self presentViewController:nav_orderVc animated:YES completion:nil];
    } else {
        [self performSegueWithIdentifier:@"loginSegue" sender:nil];
    }
}

- (IBAction)fourOrderButtonPress:(UIButton *)sender {
    if ([BDAccountManagerModel shareInstance].login) {
        NSInteger index;
        switch (sender.tag) {
            case 201:
                index = 1;
                break;
            case 202:
                index = 2;
                break;
            case 203:
                index = 3;
                break;
            case 204:
                index = 4;
                break;
            default:
                break;
        }
        UIStoryboard *stroyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
        BDOrderNavigationController *nav_orderVc = [stroyboard instantiateViewControllerWithIdentifier:@"NavOrderStoryboardID"];
        nav_orderVc.mTabBarController = self.tabBarController;
        BDOrderHomeViewController *orderVc = (BDOrderHomeViewController *)nav_orderVc.topViewController;
        orderVc.selectIndex = index;
        orderVc.block = ^(NSString *str){
            if ([str isEqualToString:@"success"]) {// 用于从订单返回首页
                self.tabBarController.selectedIndex = 0;
            }
        };
        [self presentViewController:nav_orderVc animated:YES completion:nil];
    } else {
        [self performSegueWithIdentifier:@"loginSegue" sender:nil];
    }
}

- (IBAction)callPhoneButton:(UIButton *)sender {
    
}

- (IBAction)messageButton:(UIButton *)sender {
    [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"Still in process", nil)];
}

- (IBAction)youhuiButtonPressed:(UIButton *)sender {
    if ([BDAccountManagerModel shareInstance].login) {
        UIStoryboard *stroyboard = [UIStoryboard storyboardWithName:@"ThirdStoryboard" bundle:[NSBundle mainBundle]];
        UINavigationController *nav_vc = [stroyboard instantiateViewControllerWithIdentifier:@"NavYouHuiStoryboardID"];
        [self presentViewController:nav_vc animated:YES completion:nil];
    } else {
        [self performSegueWithIdentifier:@"loginSegue" sender:nil];
    }
    
}



@end
